//
//  HealthEatViewController.m
//  Food
//
//  Created by dlios on 15/7/14.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "HealthEatViewController.h"
#import "HealthLearnViewController.h"
#import "HealthObject.h"
#import "MyCollectionViewCell.h"
#import "TimeCell.h"
#import "TimeViewController.h"

@interface HealthEatViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate>

@property (nonatomic ,retain) UIScrollView *scoll;
@property (nonatomic, retain) UIScrollView *bigScroll;
@property (nonatomic, retain) UIImageView *indexView;
@property (nonatomic, retain) NSMutableArray *kindArr;
@property (nonatomic, retain) NSMutableArray *sectionNumber;
@property (nonatomic, retain) NSMutableArray *timeArr;
@property (nonatomic, retain) NSString *time;
@property (nonatomic, retain) UILabel *name;
@property (nonatomic, retain) UILabel *subtitle;
@property (nonatomic, retain) UILabel *info;
@property (nonatomic, retain) UILabel *knowLabel;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, assign) int a;
@property (nonatomic, retain) MBProgressHUD *progress;

@end

@implementation HealthEatViewController

- (void)dealloc
{
    [super dealloc];
    [_scoll release];
    [_bigScroll release];
    [_indexView release];
    [_time release];
    [_name release];
    [_subtitle release];
    [_info release];
    [_knowLabel release];
    [_table release];
    [_url release];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.view.autoresizesSubviews = NO;
    
    //    [self.navigationItem setLeftBarButtonItem:nil animated:NO];
    [self createSegmentControll];
    [self createLittleScrollView];
    
    self.bigScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 45, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 50 - 50)];
    self.bigScroll.delegate = self;
    self.bigScroll.tag = 20000;
    self.bigScroll.backgroundColor = [UIColor whiteColor];
    self.bigScroll.contentSize = CGSizeMake(0,568);
    [self.view addSubview:self.bigScroll];
    [_bigScroll release];
    
    UIImageView *picture = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, 280, 190)];
    picture.image = [UIImage imageNamed:@"yangsheng"];
    [self.bigScroll addSubview:picture];
    [picture release];
    
    self.name = [[UILabel alloc] initWithFrame:CGRectMake(110, 210, 100, 20)];
    self.name.textAlignment = NSTextAlignmentCenter;
    self.name.font = [UIFont boldSystemFontOfSize:20];
    [self.bigScroll addSubview:self.name];
    [_name release];
    
    self.subtitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 260, 280, 60)];
    self.subtitle.numberOfLines = 0;
    self.subtitle.font = [UIFont boldSystemFontOfSize:17];
    [self.bigScroll addSubview:self.subtitle];
    [_subtitle release];
    
    self.info = [[UILabel alloc] initWithFrame:CGRectMake(20, 350, 280, 0)];
    self.info.numberOfLines = 0;
    self.info.font = [UIFont systemFontOfSize:16];
    self.info.textColor = [UIColor grayColor];
    [self.bigScroll addSubview:self.info];
    [_info release];
    
    self.knowLabel = [[UILabel alloc] init];
    [self.bigScroll addSubview:self.knowLabel];
    [_knowLabel release];
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(10, 0, 300, 0) style:UITableViewStylePlain];
    _table.dataSource = self;
    _table.delegate = self;
    [_table registerClass:[TimeCell class] forCellReuseIdentifier:@"cell"];
    [self.bigScroll addSubview:_table];
    [_table release];
   
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
   }else
   {
       [self createProgressView];
       [self getMain];
   }
    
}


- (void)getMain
{
    
       // 进来先进行一次网络请求 判断是甚么时间
    [AFNet connectNetGetDataWithURLString:@"http://api.xiangha.com/home5/getIndexData?type=newData" parameters:nil finishblock:^(id result) {
        
        [self.progress hide:YES];
        NSString *str1 = [[[result objectForKey:@"data"] objectForKey:@"whatHour"] objectForKey:@"title"];

        self.url = [str1 substringToIndex:2];
        if ([self.url isEqualToString:@"巳时"]) {
            self.a = 5;
        }if ([self.url isEqualToString:@"子时"]) {
            self.a = 0;
        }if ([self.url isEqualToString:@"丑时"]) {
            self.a = 1;
        }if ([self.url isEqualToString:@"寅时"]) {
            self.a = 2;
        }if ([self.url isEqualToString:@"卯时"]) {
            self.a = 3;
        }if ([self.url isEqualToString:@"辰时"]) {
            self.a = 4;
        }if ([self.url isEqualToString:@"午时"]) {
            self.a = 6;
        }if ([self.url isEqualToString:@"未时"]) {
            self.a = 7;
        }if ([self.url isEqualToString:@"申时"]) {
            self.a = 8;
        }if ([self.url isEqualToString:@"酉时"]) {
            self.a = 9;
        }if ([self.url isEqualToString:@"戌时"]) {
            self.a = 10;
        }if ([self.url isEqualToString:@"亥时"]) {
            self.a = 11;
        }
        
        
        if (self.a >= 2 && self.a <= 9 ) {
            self.scoll.contentOffset = CGPointMake(self.a * 100-5, 0);
        }else if(self.a > 9)
        {
            self.scoll.contentOffset = CGPointMake(9 *100-5, 0);
        }
        self.indexView.frame = CGRectMake(10+ 100 * self.a, 0, 100, 40);
        
        
        [self getdata];
        
    }];
    
}


- (void)getdata
{
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        return;
    }else{

    NSString *str = @"http://api.xiangha.com/zhishi5/getNousList?type=whatHour&name=";
    NSString *url = [NSString stringWithFormat:@"%@%@",str,self.url];
    self.kindArr = [NSMutableArray array];
    [AFNet connectNetGetDataWithURLString:url parameters:nil finishblock:^(id result) {
        [self.progress hide:YES];
        NSDictionary *dic = [result objectForKey:@"data"];
        HealthObject *object = [[HealthObject alloc] initWithDic:dic];
        [self.kindArr addObject:object];
        
        [self shuaxin];
        [self.table reloadData];
        [object release];
    }];
        
    }
}

// 刷新label
- (void)shuaxin
{
    _name.text = nil;
    _subtitle.text = nil;
    _info.text = nil;
    _knowLabel.text = nil;
    
    HealthObject *object = self.kindArr.lastObject;
    _name.text = object.name;
    _subtitle.text = object.subtitle;
    [_subtitle sizeToFit];
    _info.text = object.info;
    self.info.frame = CGRectMake(20, 250 + self.subtitle.frame.size.height + 30, 280, 0);
    [_info sizeToFit];
    
    self.knowLabel.frame = CGRectMake(SCREEN_WIDTH/2 - 70, self.info.frame.origin.y + self.info.frame.size.height + 50, 140, 20);
    self.knowLabel.text = [NSString stringWithFormat:@"%@养生知识",object.name];
    self.knowLabel.textAlignment = NSTextAlignmentCenter;
    self.table.frame = CGRectMake(10, self.knowLabel.frame.origin.y + 30, 300, 60 * object.nous.count);
    self.bigScroll.contentSize = CGSizeMake(0, _name.frame.size.height + _subtitle.frame.size.height + _info.frame.size.height + _table.frame.size.height + 350);

    
}




- (void)createProgressView
{
    self.progress = [[MBProgressHUD alloc] initWithView:self.view];
    self.progress.labelText = @"稍等";
    self.progress.detailsLabelText = @"正在加载...";
    self.progress.delegate = self;
    [self.progress show:YES];
    [self.view addSubview:self.progress];
    
}


#pragma mark- 创建segmentControll
- (void)createSegmentControll
{
    
    NSArray *arr = [NSArray arrayWithObjects:@"健康",@"养生知识", nil];
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:arr];
    self.navigationItem.titleView = segment;
    segment.tintColor = [UIColor redColor];
    // 默认选中的下标
    segment.selectedSegmentIndex = 0;
    // 绑定方法
    [segment addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    [segment release];
}
#pragma mark- segment关联的方法

- (void)controllerPressed:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 1) {
        HealthLearnViewController *learn = [[HealthLearnViewController alloc] init];
        [self.navigationController pushViewController:learn animated:NO];
    }
    
    segment.selectedSegmentIndex = 0;
}

- (void)createLittleScrollView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.timeArr = [NSMutableArray arrayWithObjects:@"子时养胆",@"丑时养肝",@"寅时养肺",@"卯时养大肠",@"辰时养胃",@"巳时养脾",@"午时养心",@"未时养小肠",@"申时养膀胱",@"酉时养肾",@"戌时养心包",@"亥时养三焦", nil];
    
    self.scoll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.scoll.backgroundColor = RGBCOLOR(243, 243, 243);
    self.scoll.tag = 10000;
    self.scoll.contentSize = CGSizeMake(1220, 0);
    self.scoll.showsHorizontalScrollIndicator = NO;
    self.scoll.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scoll];
    [_scoll release];
    
    self.indexView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 100, 40)];
    self.indexView.image = [UIImage imageNamed:@"red_line_and_shadow"];
    [self.scoll addSubview:self.indexView];
    [_indexView release];
    
    for (int i = 0; i < self.timeArr.count; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i + 1000;
        [button setTitle:self.timeArr[i] forState:UIControlStateNormal];
        button.frame = CGRectMake(10 + i * 100, 10, 100, 20);
        [button addTarget:self action:@selector(Clicked:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.scoll addSubview:button];
        if (button.tag == 1002) {
        
        }
        
    }
}

#pragma mark- button点击
- (void)Clicked:(UIButton *)button
{
    
    _name.text = nil;
    _subtitle.text = nil;
    _info.text = nil;
    _knowLabel.text = nil;
    
    for (int i = 0; i < self.timeArr.count; i ++) {
        if (button.tag == i +1000) {
            
            [UIView animateWithDuration:0.3 animations:^{
                self.indexView.frame = CGRectMake(10+ 100 * i, 0, 100, 40);
               
            }];
            if (i >2  && i <= self.timeArr.count -3 ) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.scoll.contentOffset = CGPointMake( i*80, 0);
                    
                }];
            }
            
            NSString *str = button.currentTitle;
            NSString *str1 = [str substringToIndex:2];
            self.time = str1;
            [self getdataagin];
        }
    }
}



- (void)getdataagin
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
       
    }else{
    NSString *str = @"http://api.xiangha.com/zhishi5/getNousList?type=whatHour&name=";
    NSString *url = [NSString stringWithFormat:@"%@%@",str,self.time];
    self.kindArr = [NSMutableArray array];
    [AFNet connectNetGetDataWithURLString:url parameters:nil finishblock:^(id result) {
        [self.progress hide:YES];
        NSDictionary *dic = [result objectForKey:@"data"];
        HealthObject *object = [[HealthObject alloc] initWithDic:dic];
        [self.kindArr addObject:object];
        [object release];
        [self.table reloadData];
        [self shuaxin];
    }];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HealthObject *object = self.kindArr.lastObject;
    
    return object.nous.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    HealthObject *object = self.kindArr.lastObject;
    NSMutableArray *arr = object.nous;
    NSString *imag = [arr[indexPath.row] objectForKey:@"img"];
    [cell.img setImageWithURL:[NSURL URLWithString:imag] placeholderImage:[UIImage imageNamed:@""]];
    cell.title.text = [arr[indexPath.row] objectForKey:@"title"];
    cell.content.text = [arr[indexPath.row] objectForKey:@"content"];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TimeViewController *timeVC = [[TimeViewController alloc] init];
    timeVC.hidesBottomBarWhenPushed = YES;
    HealthObject *model = self.kindArr.lastObject;
    NSString *str = [NSString stringWithFormat:@"%@",[model.nous[indexPath.row] objectForKey:@"code"]];
    timeVC.ID = str;
    timeVC.img = [model.nous[indexPath.row] objectForKey:@"img"];
    timeVC.decripe = [model.nous[indexPath.row] objectForKey:@"content"];
    [self.navigationController pushViewController:timeVC animated:YES];
    
}

- (void)data
{
    [self getMain];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
